<template>
    <el-drawer
    :title="!dataForm.id ? '新增' : '修改'"
    direction="rtl"
    ref="drawer"
    size="48%"
    :visible.sync="visible">
    <div class="demo-drawer__header">
      <el-row>
        <el-col :span="12" style="text-align:center;">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl()"
            :with-credentials="true"
            :limit="1"
            :headers="myHeader"
            :show-file-list="false"
            :on-error="onError"
            :on-success="handleAvatarSuccess">
            <img v-if="avatarPic" :src="remoteUrl + avatarPic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-col>
        <el-col :span="12">
          <el-button size="mini" @click="visible = false">取 消</el-button>
          <el-button type="primary" plain size="mini" @click="dataFormSubmit()">确 定</el-button>
        </el-col>
      </el-row>
    </div>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="所在部门" prop="deptId">
            <el-tree-select
              style="width:100%"
              :data="treeData"
              v-model="dataForm.deptId"
              node-key="id"
              placeholder="请选择部门"
              @focus="initOrgTree"
              />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="dataForm.name" placeholder="姓名"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="dataForm.idCard" placeholder="身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="dataForm.gender" placeholder="性别" style="width:100%">
                <el-option
                  v-for="item in genders"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="dataForm.mobile" placeholder="手机号码" maxlength="11"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学历">
            <el-select v-model="dataForm.academic" placeholder="请选择学历" style="width:100%">
                <el-option
                  v-for="item in academics"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="入职时间" prop="entryTime">
            <el-date-picker type="date" v-model="dataForm.entryTime" placeholder="入职时间" style="width:100%"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同到期日期" prop="contractExpirationTime">
            <el-date-picker type="date" v-model="dataForm.contractExpirationTime" placeholder="合同到期日期" style="width:100%"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="员工成长日志" prop="remark">
            <el-input type="textarea" :rows="6" v-model="dataForm.remark" placeholder="请填写情况说明"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="上传简历">
            <el-upload
              :action="uploadUrl()"
              :headers="myHeader"
              :limit="1"
              :on-success="onContractSuccess"
              :on-error="onError"
              ref="certiUpload"
              list-type="picture-card">
                <i class="el-icon-plus"></i>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过800kb</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-drawer>
</template>

<script>
  import Vue from "vue"
  import ElTreeSelect from "@/components/treeSelect/index.vue"
  export default {
    name:'CertificateUpdate',
    data () {
      return {
        visible: false,
        treeData: [],
        dataForm: {
          id: 0,
          deptId: '',
          tenantId: '',
          name: '',
          idCard: '',
          gender: '',
          mobile: '',
          academic: '',
          jobGrade: '',
          entryTime: '',
          contractExpirationTime: '',
          remark: ''
        },
        academics: [{
          value: '博士',
          label: '博士'
        }, {
          value: '硕士',
          label: '硕士'
        }, {
          value: '本科',
          label: '本科'
        }, {
          value: '专科',
          label: '专科'
        }, {
          value: '高职高专',
          label: '高职高专'
        }, {
          value: '中专',
          label: '中专'
        }, {
          value: '高中',
          label: '高中'
        }, {
          value: '初中',
          label: '初中'
        }, {
          value: '小学',
          label: '小学'
        }, {
          value: '其他',
          label: '其他'
        }],
        genders:[{
          value: 1,
          label: '男'
        },{
          value: 2,
          label: '女'
        }],
        dataRule: {
          deptId: [
            { required: true, message: '请选择部门', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请填写姓名', trigger: 'blur' }
          ],
          idCard: [
            { required: true, message: '请填写身份证号', trigger: 'blur' },
            { validator: this.validID, trigger: 'blur' }
          ],
          mobile: [
            { required: true, len:11, message: '请填写正确的手机号码', trigger: 'blur' }
          ],
          academic: [
            { required: true, message: '请选择学历', trigger: 'blur' }
          ],
          jobGrade: [
            { required: true, message: '请选择职称', trigger: 'blur' }
          ],
          entryTime: [
            { required: true, message: '请选择入职时间', trigger: 'blur' }
          ],
          contractExpirationTime: [
            { required: true, message: '请选择合同到期日期', trigger: 'blur' }
          ]
        },
        tenantId: '',
        remoteUrl: '',
        baseInfoPics: [],
        avatarPic: ''
      }
    },
    components: {
      ElTreeSelect
    },
    computed: {
      myHeader(){
        return {"token":Vue.cookie.get('token')}
      }
    },
    methods: {
      init (id, tenantId) {
        this.tenantId = tenantId || 0
        this.dataForm.id = id || 0
        this.avatarPic = ''
        this.visible = true
        this.initOrgTree()
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/certificate/employeeInfo/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.remoteUrl = data.remoteUrl
                this.avatarPic = data.e.avatarPic
                this.dataForm.id = data.e.id
                this.dataForm.tenantId = data.e.tenantId
                this.dataForm.deptId = data.e.deptId
                this.dataForm.name = data.e.name
                this.dataForm.idCard = data.e.idCard
                this.dataForm.gender = data.e.gender
                this.dataForm.mobile = data.e.mobile
                this.dataForm.academic = data.e.academic
                this.dataForm.jobGrade = data.e.jobGrade
                this.dataForm.entryTime = data.e.entryTime
                this.dataForm.contractExpirationTime = data.e.contractExpirationTime
                this.dataForm.remark = data.e.remark
                
                this.baseInfoPics = []
                if(data.e.contractInfoList && data.e.contractInfoList.length > 0){
                  for(var i=0; i < data.e.contractInfoList.length; i++){
                    this.baseInfoPics.push(data.e.contractInfoList[i].path)
                  }
                }
              }
            })
          }
        })
      },
      errorHandler() {
        return true
      },
      handleAvatarSuccess(response, file, fileList){
        this.remoteUrl = response.remoteUrl
        this.avatarPic = response.fileName
      },
      onContractSuccess(response, file, fileList){
        this.remoteUrl = response.remoteUrl
        this.baseInfoPics = []
        for(var i=0; i<fileList.length; i++){
          this.baseInfoPics.push(fileList[i].response.fileName)
        }
      },
      onError(err, file, fileList){
        this.$message.error("上传失败")
      },
      uploadUrl(){
        return this.$http.adornUrl('/certificate/employeeInfo/upload')
      },
       // 身份证验证
      async validID(rule,value,callback){
        // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X 
        let reg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (reg.test(value)) {
          await this.go(value);
          callback()
        } else {
          callback(new Error('身份证号码不正确'))
        }
      },
      // 实现自动生成生日，性别，年龄
      go(iden) {
        let sex = null;
        let birth = null;
        let myDate = new Date();
        let month = myDate.getMonth() + 1;
        let day = myDate.getDate();
        let age = 0;
 
        age = myDate.getFullYear() - iden.substring(6, 10) - 1;
        sex = iden.substring(16,17);
        birth = iden.substring(6,10)+"-"+iden.substring(10,12)+"-"+iden.substring(12,14);
        if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;

        if(sex%2 === 0)
          sex = 2;
        else
          sex = 1;
        this.dataForm.gender = sex;
        //this.baseInfo.age = age;
        //this.baseInfo.birthday = birth;
        //this.baseInfo.birthplace = this.area[iden.substring(0,2)];
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/certificate/employeeInfo/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'tenantId': this.dataForm.tenantId,
                'deptId': this.dataForm.deptId,
                'name': this.dataForm.name,
                'idCard': this.dataForm.idCard,
                'gender': this.dataForm.gender,
                'mobile': this.dataForm.mobile,
                'academic': this.dataForm.academic,
                'jobGrade': this.dataForm.jobGrade,
                'entryTime': this.$dateFormat(this.dataForm.entryTime),
                'contractExpirationTime': this.$dateFormat(this.dataForm.contractExpirationTime),
                'remark': this.dataForm.remark,
                'constractPic': this.baseInfoPics.join(','),
                'avatarPic': this.avatarPic
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      initOrgTree() {
        this.$http({
          url: this.$http.adornUrl('/tenant/tenantDeptInfo/tree'),
          method: 'get',
          params: this.$http.adornParams({'tenandId':this.tenantId})
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.treeData = [data.deptInfo]
          } else {
            this.treeData = []
          }
        })
      }
    }
  }
</script>

<style lang="scss">
    .demo-drawer {
        &__content {
            display: flex;
            flex-direction: column;
            height: 100%;
            form {
                flex: 1;
            }
        }
        &__footer {
            display: flex;
            button {
                flex: 1;
            }
        }
        &__header {
            text-align:right;
            margin-bottom:20px;
            width:100%;
        }
    }
    .el-drawer__body {
        padding: 20px;
    }
    .el-drawer__body{
      overflow-x:hidden;
      overflow-x:auto;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 50px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 70px;
      height: 70px;
      line-height: 70px;
      text-align: center;
    }
    .avatar {
      width: 70px;
      height: 70px;
      display: block;
    }
    .el-input__inner{
      height: 36px;
    }
</style>
